<template>
  <view class="s-file-upload" @tap="handleUpload">
    <slot>
      <view class="default-upload">
        <image class="preview-image" :src="value || defaultImage" :mode="imageMode"></image>
        <view class="upload-mask">
          <text class="upload-icon">+</text>
        </view>
      </view>
    </slot>
  </view>
</template>

<script>
export default {
  name: 'SFileUpload',
  props: {
    // 当前值（文件URL）
    value: {
      type: String,
      default: ''
    },
    // 默认图片
    defaultImage: {
      type: String,
      default: '/static/images/default-avatar.png'
    },
    // 图片显示模式
    imageMode: {
      type: String,
      default: 'aspectFill'
    },
    // 上传接口地址
    uploadUrl: {
      type: String,
      default: ''
    },
    // 文件类型
    fileType: {
      type: String,
      default: 'image'
    },
    // 文件数量限制
    count: {
      type: Number,
      default: 1
    },
    // 文件大小限制（MB）
    maxSize: {
      type: Number,
      default: 5
    }
  },
  
  methods: {
    // 处理上传
    handleUpload() {
      if (this.fileType === 'image') {
        this.chooseImage();
      } else {
        this.chooseFile();
      }
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: this.count,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 检查文件大小
          uni.getFileInfo({
            filePath: tempFilePath,
            success: (fileInfo) => {
              const fileSizeMB = fileInfo.size / (1024 * 1024);
              if (fileSizeMB > this.maxSize) {
                uni.showToast({
                  title: `文件大小不能超过${this.maxSize}MB`,
                  icon: 'none'
                });
                return;
              }
              
              this.uploadFile(tempFilePath);
            }
          });
        }
      });
    },
    
    // 选择文件
    chooseFile() {
      // #ifdef APP-PLUS || H5
      uni.chooseFile({
        count: this.count,
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.uploadFile(tempFilePath);
        }
      });
      // #endif
      
      // #ifdef MP
      uni.showToast({
        title: '小程序暂不支持选择文件',
        icon: 'none'
      });
      // #endif
    },
    
    // 上传文件
    uploadFile(filePath) {
      // 显示上传中
      uni.showLoading({
        title: '上传中...'
      });
      
      // 上传图片
      uni.uploadFile({
        url: this.uploadUrl || 'https://api.example.com/upload', // 替换为实际的上传接口
        filePath: filePath,
        name: 'file',
        success: (uploadRes) => {
          try {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 0 && data.data) {
              // 上传成功，触发事件
              this.$emit('input', data.data.url);
              this.$emit('success', data.data);
            } else {
              this.$emit('error', data);
              uni.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              });
            }
          } catch (e) {
            this.$emit('error', e);
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          this.$emit('error', err);
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  }
};
</script>

<style lang="scss">
.s-file-upload {
  display: inline-block;
  
  .default-upload {
    width: 70px;
    height: 70px;
    border-radius: 35px;
    overflow: hidden;
    position: relative;
    
    .preview-image {
      width: 100%;
      height: 100%;
    }
    
    .upload-mask {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 24px;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .upload-icon {
      color: #fff;
      font-size: 16px;
    }
  }
}
</style>